package com.code.penguin.bots;

import com.code.penguin.enums.SystemKeyEnum;
import com.code.penguin.managers.HttpManager;
import com.code.penguin.models.*;
import com.code.penguin.services.*;
import com.code.penguin.utils.ValidatorUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.telegram.telegrambots.bots.TelegramLongPollingBot;
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
import org.telegram.telegrambots.meta.api.objects.Message;
import org.telegram.telegrambots.meta.api.objects.Update;
import org.telegram.telegrambots.meta.api.objects.replykeyboard.InlineKeyboardMarkup;
import org.telegram.telegrambots.meta.api.objects.replykeyboard.ReplyKeyboardMarkup;
import org.telegram.telegrambots.meta.api.objects.replykeyboard.buttons.InlineKeyboardButton;
import org.telegram.telegrambots.meta.api.objects.replykeyboard.buttons.KeyboardRow;
import org.telegram.telegrambots.meta.exceptions.TelegramApiException;

import java.util.ArrayList;
import java.util.List;

/**
 * 任务机器人
 * telegram bot 接受信息有2种实现方式
 * Long Polling Bot 长轮询的方式,每隔一段时间主动请求telegram，继承 TelegramLongPollingBot
 * webHook 方式,telegram 主动下发
 *
 * @author xiaoyaowang
 */
public class TaskRobot extends TelegramLongPollingBot {

    private static Logger logger = LoggerFactory.getLogger(TaskRobot.class);

    private String menuFirstButtonText;

    private String menuSecondButtonText;

    private String menuThirdButtonText;

    private String menuFourthButtonText;

    private String replyButtonText;

    private String replyDoneText;

    private String errorText;

    private String listenJoinGroupUrlPrefix;

    private String listenJoinGroupName;

    private RobotChatService robotChatService;

    private RobotTaskService robotTaskService;

    private ChatMemberGroupService chatMemberGroupService;

    private VerifiedAddrService verifiedAddrService;

    private RobotTaskCheckService robotTaskCheckService;

    private ChatLinkService chatLinkService;

    private RobotSystemService robotSystemService;

    private ChatBanService chatBanService;

    private ChatEmailService chatEmailService;

    private ChatDiscordService chatDiscordService;

    private ChatCollectService chatCollectService;

    private String robotName;

    private String robotToken;

    private ChatTwitterService chatTwitterService;

    private HttpManager httpManager;

    private String walletDownLoadUrl;

    public void setChatBanService(ChatBanService chatBanService) {
        this.chatBanService = chatBanService;
    }

    public void setVerifiedAddrService(VerifiedAddrService verifiedAddrService) {
        this.verifiedAddrService = verifiedAddrService;
    }

    public void setChatMemberGroupService(ChatMemberGroupService chatMemberGroupService) {
        this.chatMemberGroupService = chatMemberGroupService;
    }

    public void setMenuFirstButtonText(String menuFirstButtonText) {
        this.menuFirstButtonText = menuFirstButtonText;
    }

    public void setMenuSecondButtonText(String menuSecondButtonText) {
        this.menuSecondButtonText = menuSecondButtonText;
    }

    public void setRobotSystemService(RobotSystemService robotSystemService) {
        this.robotSystemService = robotSystemService;
    }

    public void setMenuThirdButtonText(String menuThirdButtonText) {
        this.menuThirdButtonText = menuThirdButtonText;
    }

    public void setMenuFourthButtonText(String menuFourthButtonText) {
        this.menuFourthButtonText = menuFourthButtonText;
    }

    public void setListenJoinGroupUrlPrefix(String listenJoinGroupUrlPrefix) {
        this.listenJoinGroupUrlPrefix = listenJoinGroupUrlPrefix;
    }

    public void setListenJoinGroupName(String listenJoinGroupName) {
        this.listenJoinGroupName = listenJoinGroupName;
    }

    public void setReplyDoneText(String replyDoneText) {
        this.replyDoneText = replyDoneText;
    }

    public void setReplyButtonText(String replyButtonText) {
        this.replyButtonText = replyButtonText;
    }

    public void setErrorText(String errorText) {
        this.errorText = errorText;
    }

    public void setRobotName(String robotName) {
        this.robotName = robotName;
    }

    public void setRobotToken(String robotToken) {
        this.robotToken = robotToken;
    }

    public void setRobotChatService(RobotChatService robotChatService) {
        this.robotChatService = robotChatService;
    }

    public void setRobotTaskService(RobotTaskService robotTaskService) {
        this.robotTaskService = robotTaskService;
    }

    public void setHttpManager(HttpManager httpManager) {
        this.httpManager = httpManager;
    }

    public void setRobotTaskCheckService(RobotTaskCheckService robotTaskCheckService) {
        this.robotTaskCheckService = robotTaskCheckService;
    }

    public void setChatTwitterService(ChatTwitterService chatTwitterService) {
        this.chatTwitterService = chatTwitterService;
    }

    public void setChatLinkService(ChatLinkService chatLinkService) {
        this.chatLinkService = chatLinkService;
    }

    public void setChatEmailService(ChatEmailService chatEmailService) {
        this.chatEmailService = chatEmailService;
    }

    public void setChatDiscordService(ChatDiscordService chatDiscordService) {
        this.chatDiscordService = chatDiscordService;
    }

    public void setChatCollectService(ChatCollectService chatCollectService) {
        this.chatCollectService = chatCollectService;
    }

    public void setWalletDownLoadUrl(String walletDownLoadUrl) {
        this.walletDownLoadUrl = walletDownLoadUrl;
    }

    /**
     * 监听更新接收信息事件
     *
     * @param update 该对象表示传入的更新，比如接收到用户发来的新消息，就会获得新的更新
     */
    @Override
    public void onUpdateReceived(Update update) {
        logger.info("task bot start work,execute onUpdateReceived method，update:{}", update.toString());
        try {
            if (update.hasMessage()) {
                Message messageText = update.getMessage();
                if (null != messageText) {
                    Long chatIdLong = messageText.getChatId();
                    if (null != chatIdLong) {
                        String chatId = chatIdLong.toString();
                        // 插入用户或者群组与机器人的绑定关系
                        RobotChat robotChat = new RobotChat();
                        robotChat.setChatId(chatId);
                        robotChat.setRobotName(robotName);
                        robotChatService.insertRobotChat(robotChat);
                        String stopRobot = robotSystemService.getSystemValueBySystemKey(SystemKeyEnum.STOP_ROBOT.name());
                        if ("1".equals(stopRobot)) {
                            SendMessage sendMessage = new SendMessage();
                            sendMessage.setChatId(chatId);
                            sendMessage.setText(robotSystemService.getSystemValueBySystemKey(SystemKeyEnum.STOP_ROBOT_MESSAGE.name()));
                            execute(sendMessage);
                            return;
                        }
                        if (messageText.hasText()) {
                            // 查看用户是否被封禁
                            if (robotTaskCheckService.whetherBanedByChatId(chatId)
                                    || chatBanService.whetherExistChatBanByChatId(chatId)) {
                                SendMessage sendMessage = new SendMessage();
                                sendMessage.setChatId(chatId);
                                sendMessage.setText(robotSystemService.getSystemValueBySystemKey(SystemKeyEnum.BAN.name()));
                                execute(sendMessage);
                                return;
                            }
                            String text = messageText.getText();
                            logger.info("chatId {} send message text:{}", chatId, text);
                            int taskMaxSort = robotTaskService.getFinishedTaskMaxSort(chatId);
                            // 返回到菜单页面
                            if (text.equals(replyButtonText)) {
                                backMenuPage(chatId);
                            } else {
                                // 点击菜单页面的Earn Pen按钮进入Earn Pen菜单页
                                if (text.equals(menuFirstButtonText)) {
                                    backEarnPenMenuPage(chatId);
                                }
                                // 点击菜单页面的Pen Info 按钮
                                else if (text.equals(menuSecondButtonText)) {
                                    sendPenDetailMessage(chatId);
                                }
                                // 点击菜单页面的Wallet DownLoad 按钮
                                else if (text.equals(menuThirdButtonText)) {
                                    sendPenDownloadMessage(chatId);
                                }
                                // 点击菜单页面的My rewards 按钮
                                else if (text.equals(menuFourthButtonText)) {
                                    sendMyRewardsMessage(chatId);
                                }
                                // 执行任务
                                else {
                                    // 是否参加过空投任务
                                    Integer airdropFlag = whetherAirdrop(chatId);
                                    if (airdropFlag == 1) {
                                        return;
                                    }
                                    // 第一个任务
                                    if (taskMaxSort < 1) {
                                        // 处理第一个任务
                                        handleFirstTask(chatId, text);
                                        return;
                                    }

                                    // 继续第二个任务
                                    if (taskMaxSort == 1) {
                                        // 处理第二个任务
                                        handleSecondTask(chatId, text);
                                        return;
                                    }

                                    // 继续第三个任务
                                    if (taskMaxSort == 2) {
                                        // 处理第3个任务
                                        handleThirdTask(chatId, text);
                                        return;
                                    }

                                    // 继续第4个任务
                                    if (taskMaxSort == 3) {
                                        // 处理第4个任务
                                        handleFourthTask(chatId, text);
                                        return;
                                    }

                                    // 处理第五个任务
                                    if (taskMaxSort == 4) {
                                        // 处理第5个任务
                                        handleFifthTask(chatId, text);
                                        return;
                                    }

                                    // 处理第六个任务
                                    if (taskMaxSort == 5) {
                                        // 处理第6个任务
                                        handleSixthTask(chatId);
                                        return;
                                    }

                                    // 任务都已完成
                                    if (taskMaxSort == 6) {
                                        sendCongratulationMessage(chatId);
                                    }

                                }
                            }
                        }


                    }
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("onUpdateReceived error:", e);
        }

    }

    /**
     * 获取电报机器人名称，在进入telegram账户向@BotFather发送/newbot指令的时候输入的机器人的名字，每一个机器人都是唯一的
     *
     * @return 电报机器人名称
     */
    @Override
    public String getBotUsername() {
        return robotName;
    }

    /**
     * 获取电报机器人的token，在进入telegram账户向@BotFather发送/newbot指令的时候BotFather返回给机器人的token，每一个机器人都是唯一的
     *
     * @return 电报机器人的token
     */
    @Override
    public String getBotToken() {
        return robotToken;
    }

    /**
     * 是否已参加空投
     *
     * @param chatId 聊天id
     * @throws TelegramApiException 异常
     */
    private Integer whetherAirdrop(String chatId) throws TelegramApiException {
        AirdropRecord airdropRecord = new AirdropRecord();
        boolean existsAirdropRecord = robotTaskService.existsAirdropRecordByCondition(airdropRecord);
        if (existsAirdropRecord) {
            sendAirdropMessage(chatId);
            return 1;
        }
        return 0;
    }

    /**
     * 发送已空投的消息
     *
     * @param chatId 聊天id
     * @throws TelegramApiException
     */
    private void sendAirdropMessage(String chatId) throws TelegramApiException {
        SendMessage message = new SendMessage();
        message.setChatId(chatId);
        message.setText("You have already participated in the event.");
        execute(message);
    }

    /**
     * 处理第一步任务
     *
     * @param chatId 聊天id
     * @param text   发送的文本
     * @throws TelegramApiException 异常
     */
    private void handleFirstStepTask(String chatId, String text) throws TelegramApiException {
        SendMessage sendMessage = new SendMessage();
        sendMessage.setChatId(chatId);
        sendMessage.setText(text);
        // 设置带有回复选项的自定义键盘
        ReplyKeyboardMarkup replyKeyboardMarkup = getCommonReplyKeyboardMarkup(1);
        sendMessage.setReplyMarkup(replyKeyboardMarkup);
        execute(sendMessage);
    }

    /**
     * 处理第2步任务
     *
     * @param chatId 聊天id
     * @param text   发送的文本
     * @throws TelegramApiException 异常
     */
    private void handleSecondStepTask(String chatId, String text) throws TelegramApiException {
        SendMessage secondTaskMessage = new SendMessage();
        secondTaskMessage.setChatId(chatId);
        secondTaskMessage.setText(text);
        // 增加内联按钮
        List<List<InlineKeyboardButton>> keyboardList = new ArrayList<>();
        List<InlineKeyboardButton> keyboardButtons = new ArrayList<>();
        // 此对象表示嵌入式键盘的一个按钮，您必须完全使用可选字段之一
        InlineKeyboardButton inlineKeyboardButton = new InlineKeyboardButton();
        // 可选的。按下按钮时将打开HTTP或tg:// URL
        inlineKeyboardButton.setUrl("https://t.co/U7VWKnQZwg?amp=1");
        // 在按钮上标记文本
        inlineKeyboardButton.setText("Join Discord");
        keyboardButtons.add(inlineKeyboardButton);
        keyboardList.add(keyboardButtons);
        InlineKeyboardMarkup inlineKeyboardMarkup = new InlineKeyboardMarkup();
        // 按钮行数组，每个行由一个InlineKeyboardButton对象数组表示，这仅适用于2016年4月9日之后发布的电报版本。较旧的客户端将显示不受支持的消息。
        inlineKeyboardMarkup.setKeyboard(keyboardList);
        // 可选的。 消息附带的嵌入式键盘。 login_url按钮表示为普通url按钮。
        secondTaskMessage.setReplyMarkup(inlineKeyboardMarkup);
        execute(secondTaskMessage);

    }

    /**
     * 处理第3步任务
     *
     * @param chatId 聊天id
     * @param text   发送的文本
     * @throws TelegramApiException 异常
     */
    private void handleThirdStepTask(String chatId, String text) throws TelegramApiException {
        SendMessage thirdTaskMessage = new SendMessage();
        thirdTaskMessage.setChatId(chatId);
        thirdTaskMessage.setText(text);
        // 增加内联按钮
        List<List<InlineKeyboardButton>> keyboardList = new ArrayList<>();
        List<InlineKeyboardButton> keyboardButtons = new ArrayList<>();
        // 此对象表示嵌入式键盘的一个按钮，您必须完全使用可选字段之一
        InlineKeyboardButton inlineKeyboardButton = new InlineKeyboardButton();
        // 可选的。按下按钮时将打开HTTP或tg:// URL
        inlineKeyboardButton.setUrl("https://twitter.com/Penguin_DSN/status/1463030221347557376");
        // 在按钮上标记文本
        inlineKeyboardButton.setText("Open Twitter");
        keyboardButtons.add(inlineKeyboardButton);
        keyboardList.add(keyboardButtons);
        InlineKeyboardMarkup inlineKeyboardMarkup = new InlineKeyboardMarkup();
        // 按钮行数组，每个行由一个InlineKeyboardButton对象数组表示，这仅适用于2016年4月9日之后发布的电报版本。较旧的客户端将显示不受支持的消息。
        inlineKeyboardMarkup.setKeyboard(keyboardList);
        // 可选的。 消息附带的嵌入式键盘。 login_url按钮表示为普通url按钮。
        thirdTaskMessage.setReplyMarkup(inlineKeyboardMarkup);
        execute(thirdTaskMessage);

    }

    /**
     * 设置带有回复选项的自定义键盘
     *
     * @param showDoneButton 是否显示done按钮 0-不显示 1-显示
     * @return 带有回复选项的自定义键盘
     */
    private ReplyKeyboardMarkup getCommonReplyKeyboardMarkup(Integer showDoneButton) {
        ReplyKeyboardMarkup replyKeyboardMarkup = new ReplyKeyboardMarkup();
        //按钮行数组，每个行由一个KeyboardButton对象数组表示
        List<KeyboardRow> keyboard = new ArrayList<>();
        // 第一行
        KeyboardRow keyboardRow1 = new KeyboardRow();
        // 第一行的按钮
        if (showDoneButton == 1) {
            // 显示It's done,check it!相关的按钮
            keyboardRow1.add(replyDoneText);
        }
        keyboardRow1.add(replyButtonText);
        keyboard.add(keyboardRow1);
        replyKeyboardMarkup.setKeyboard(keyboard);
        // 可选的。请求客户垂直调整键盘大小以达到最佳适合度（例如，如果只有两行按钮，则使键盘变小）。默认为false，在这种情况下，自定义键盘的高度始终与应用程序的标准键盘相同。
        replyKeyboardMarkup.setResizeKeyboard(true);
        // 可选的。如果只想向特定用户显示键盘，请使用此参数。目标：1）在Message对象的文本中@提及的用户； 2）如果机器人的消息是回复（具有reply_to_message_id），则为原始消息的发送者。
        replyKeyboardMarkup.setSelective(true);
        // 如果需要点击一次就隐藏的键盘（但是依旧可以点击按钮显示），那么可以给 markup 构造时加入one_time_keyboard=True的参数
        //replyKeyboardMarkup.setOneTimeKeyboard(true);
        return replyKeyboardMarkup;
    }

    /**
     * 处理第一个任务
     *
     * @param chatId 聊天id
     * @param text   发送的文本
     * @throws Exception 异常
     */
    private void handleFirstTask(String chatId, String text) throws Exception {
        RobotTask robotTask = robotTaskService.getRobotTaskByTaskSort(1);
        if (null != robotTask) {
            if (!StringUtils.isBlank(text)) {
                String taskDescription = robotTask.getTaskDescription();
                if (text.contains("/start")) {
                    handleFirstStepTask(chatId, taskDescription);
                } else {
                    // 校验邮箱地址的正确性
                    if (!ValidatorUtil.isEmail(text)) {
                        handleFirstStepTask(chatId, taskDescription);
                        return;
                    }
                    // 判断邮箱地址是否已被注册
                    boolean whetherExistEmail = chatEmailService.whetherExistEmailByChatIdAndEmail(null, text);
                    if (whetherExistEmail) {
                        handleFirstStepTask(chatId, taskDescription);
                    } else {
                        RobotChatFinishTask robotChatFinishTask = new RobotChatFinishTask();
                        robotChatFinishTask.setChatId(chatId);
                        robotChatFinishTask.setTaskId(robotTask.getId());
                        robotChatFinishTask.setEmail(text);
                        int count = robotTaskService.insertRobotChatFinishTask(robotChatFinishTask);
                        if (count > 0) {
                            // 弹出步骤2
                            RobotTask robotTask2 = robotTaskService.getRobotTaskByTaskSort(2);
                            if (null != robotTask2) {
                                handleSecondStepTask(chatId, robotTask2.getTaskDescription());
                            }
                        }
                    }
                }

            }
        }
    }

    /**
     * 处理第2个任务
     *
     * @param chatId 聊天id
     * @throws TelegramApiException 异常
     */
    private void handleSecondTask(String chatId, String text) throws TelegramApiException {
        RobotTask robotTask = robotTaskService.getRobotTaskByTaskSort(2);
        if (null != robotTask) {
            String taskDescription = robotTask.getTaskDescription();
            if (text.contains("#")) {
                // Discord地址是否已提交
                boolean whetherExistDiscord = chatDiscordService.whetherExistDiscordByChatIdAndDiscordAddress(null, text);
                if (whetherExistDiscord) {
                    handleSecondStepTask(chatId, taskDescription);
                } else {
                    RobotChatFinishTask robotChatFinishTask = new RobotChatFinishTask();
                    robotChatFinishTask.setChatId(chatId);
                    robotChatFinishTask.setTaskId(robotTask.getId());
                    robotChatFinishTask.setDiscord(text);
                    int count = robotTaskService.insertRobotChatFinishTask(robotChatFinishTask);
                    if (count > 0) {
                        // 弹出第三个任务
                        RobotTask robotTask3 = robotTaskService.getRobotTaskByTaskSort(3);
                        if (null != robotTask3) {
                            handleThirdStepTask(chatId, robotTask3.getTaskDescription());
                        }
                    }
                }
            } else {
                handleSecondStepTask(chatId, taskDescription);
            }
        }
    }

    /**
     * 处理第3个任务
     *
     * @param chatId 聊天id
     * @param text   聊天text
     * @throws TelegramApiException 异常
     */
    private void handleThirdTask(String chatId, String text) throws TelegramApiException {
        RobotTask robotTask = robotTaskService.getRobotTaskByTaskSort(3);
        if (null != robotTask) {
            // 转发链接获取判断格式是否正确
            String taskDescription = robotTask.getTaskDescription();
            if (!ValidatorUtil.isTwitterLinkUrl(text)) {
                handleThirdStepTask(chatId, taskDescription);
            } else {
                // 推特id是否已提交
                String twitterId = text.substring(text.indexOf("https://twitter.com/") + 20, text.indexOf("/status/"));
                boolean whetherExistChatTwitterAccountName = chatTwitterService.whetherExistChatTwitterAccountNameByTwitterAccountName(chatId, twitterId, text);
                if (whetherExistChatTwitterAccountName) {
                    handleThirdStepTask(chatId, taskDescription);
                } else {
                    RobotChatFinishTask robotChatFinishTask = new RobotChatFinishTask();
                    robotChatFinishTask.setChatId(chatId);
                    robotChatFinishTask.setTaskId(robotTask.getId());
                    robotChatFinishTask.setTwitterAccountName(twitterId);
                    int count = robotTaskService.insertRobotChatFinishTask(robotChatFinishTask);
                    if (count > 0) {
                        RobotTask robotTask4 = robotTaskService.getRobotTaskByTaskSort(4);
                        if (null != robotTask4) {
                            handleFourthStepTask(chatId, robotTask4.getTaskDescription(), 0, 0);
                        }
                    }
                }
            }

        }
    }

    /**
     * 处理第4个任务
     *
     * @param chatId 聊天id
     * @throws TelegramApiException 异常
     */
    private void handleFourthTask(String chatId, String text) throws TelegramApiException {
        RobotTask robotTask = robotTaskService.getRobotTaskByTaskSort(4);
        if (null != robotTask) {
            String taskDescription = robotTask.getTaskDescription();
            if (!ValidatorUtil.isXwc(text)) {
                handleFourthStepTask(chatId, taskDescription, 0, 0);
            } else {
                boolean whetherXwcOnChain = httpManager.verifyCoinAddress(text);
                if (!whetherXwcOnChain) {
                    handleFourthStepTask(chatId, taskDescription, 0, 0);
                } else {
                    boolean verifyAddrSuccess = verifiedAddrService.judgeCoinAddrVerifySuccess(text);
                    if (verifyAddrSuccess) {
                        handleFourthStepTask(chatId, taskDescription, 1, 1);
                    } else {
                        RobotChatFinishTask robotChatFinishTask = new RobotChatFinishTask();
                        robotChatFinishTask.setChatId(chatId);
                        robotChatFinishTask.setTaskId(robotTask.getId());
                        robotChatFinishTask.setCoinAddr(text);
                        int count = robotTaskService.insertRobotChatFinishTask(robotChatFinishTask);
                        if (count > 0) {
                            RobotTask robotTask5 = robotTaskService.getRobotTaskByTaskSort(5);
                            if (null != robotTask5) {
                                handleFifthStepTask(chatId, robotTask5.getTaskDescription());
                            }
                        }
                    }
                }
            }

        }
    }

    /**
     * 处理第5个任务
     *
     * @param chatId 聊天id
     * @param text   发送内容
     * @throws TelegramApiException 异常
     */
    private void handleFifthTask(String chatId, String text) throws TelegramApiException {
        RobotTask robotTask = robotTaskService.getRobotTaskByTaskSort(5);
        if (null != robotTask) {
            // 判断用户是否已完成收集
            boolean whetherFinishCollect = chatCollectService.whetherFinishCollectByChatId(chatId, text);
            if (!whetherFinishCollect) {
                RobotChatFinishTask robotChatFinishTask = new RobotChatFinishTask();
                robotChatFinishTask.setChatId(chatId);
                robotChatFinishTask.setTaskId(robotTask.getId());
                robotChatFinishTask.setCollectContent(text);
                int count = robotTaskService.insertRobotChatFinishTask(robotChatFinishTask);
                if (count > 0) {
                    RobotTask robotTask6 = robotTaskService.getRobotTaskByTaskSort(6);
                    if (null != robotTask6) {
                        handleSixthStepTask(chatId, robotTask6.getTaskDescription());
                    }
                }
            } else {
                RobotTask robotTask6 = robotTaskService.getRobotTaskByTaskSort(6);
                if (null != robotTask6) {
                    handleSixthStepTask(chatId, robotTask6.getTaskDescription());
                }
            }
        }
    }

    /**
     * 处理第6个任务
     *
     * @param chatId 聊天id
     * @throws TelegramApiException 异常
     */
    private void handleSixthTask(String chatId) throws TelegramApiException {
        RobotTask robotTask = robotTaskService.getRobotTaskByTaskSort(6);
        if (null != robotTask) {
            String taskDescription = robotTask.getTaskDescription();
            ChatMemberGroup chatMemberGroup = new ChatMemberGroup();
            chatMemberGroup.setGroupUrl(listenJoinGroupUrlPrefix + listenJoinGroupName);
            chatMemberGroup.setChatId(chatId);
            // 判断用户是否加入群组
            if (!chatMemberGroupService.judgeUserWhetherJoinGroup(chatMemberGroup)) {
                // 发送第6步任务的内容
                handleSixthStepTask(chatId, taskDescription);
            } else {
                RobotChatFinishTask robotChatFinishTask = new RobotChatFinishTask();
                robotChatFinishTask.setChatId(chatId);
                robotChatFinishTask.setTaskId(robotTask.getId());
                robotChatFinishTask.setInsertRobotTaskCheckFlag(1);
                int count = robotTaskService.insertRobotChatFinishTask(robotChatFinishTask);
                if (count > 0) {
                    sendCongratulationMessage(chatId);
                }
            }

        }
    }

    /**
     * 处理第4步任务
     *
     * @param chatId            聊天id
     * @param text              发送的文本
     * @param firstMessageAgain 是否再次发送 0-不需要 1-需要
     * @throws TelegramApiException 异常
     */
    private void handleFourthStepTask(String chatId, String text, int firstMessageAgain, int coinAddrRepeatFlag) throws TelegramApiException {
        if (firstMessageAgain == 0) {
            SendMessage firstTaskOneMessage = new SendMessage();
            firstTaskOneMessage.setChatId(chatId);
            firstTaskOneMessage.setText(text);
            execute(firstTaskOneMessage);

            SendMessage secondTaskOneMessage = new SendMessage();
            secondTaskOneMessage.setChatId(chatId);
            secondTaskOneMessage.setText("If you haven't downloaded it yet pls click [Install the App] to get");

            // 增加内联按钮
            List<List<InlineKeyboardButton>> keyboardList = new ArrayList<>();
            List<InlineKeyboardButton> keyboardButtons = new ArrayList<>();
            // 此对象表示嵌入式键盘的一个按钮，您必须完全使用可选字段之一
            InlineKeyboardButton inlineKeyboardButton = new InlineKeyboardButton();
            // 可选的。按下按钮时将打开HTTP或tg:// URL
            inlineKeyboardButton.setUrl(walletDownLoadUrl);
            // 在按钮上标记文本
            inlineKeyboardButton.setText("Install the app");
            keyboardButtons.add(inlineKeyboardButton);
            keyboardList.add(keyboardButtons);
            InlineKeyboardMarkup inlineKeyboardMarkup = new InlineKeyboardMarkup();
            // 按钮行数组，每个行由一个InlineKeyboardButton对象数组表示，这仅适用于2016年4月9日之后发布的电报版本。较旧的客户端将显示不受支持的消息。
            inlineKeyboardMarkup.setKeyboard(keyboardList);
            // 可选的。 消息附带的嵌入式键盘。 login_url按钮表示为普通url按钮。
            secondTaskOneMessage.setReplyMarkup(inlineKeyboardMarkup);

            execute(secondTaskOneMessage);
        } else {
            // 发送错误文本
            SendMessage firstTaskErrorMessage = new SendMessage();
            firstTaskErrorMessage.setChatId(chatId);
            if (coinAddrRepeatFlag == 1) {
                firstTaskErrorMessage.setText("The wallet address has already been used, you need to change to another wallet address.");
            } else {
                firstTaskErrorMessage.setText(errorText);
            }
            execute(firstTaskErrorMessage);
            // 再次发送让用户提交地址的消息
            SendMessage firstTaskAgainMessage = new SendMessage();
            firstTaskAgainMessage.setChatId(chatId);
            firstTaskAgainMessage.setText(text);
            execute(firstTaskAgainMessage);
        }

    }

    /**
     * 处理第5步任务
     *
     * @param chatId          聊天id
     * @param taskDescription 任务描述
     * @throws TelegramApiException 异常
     */
    private void handleFifthStepTask(String chatId, String taskDescription) throws TelegramApiException {
        SendMessage fifthTaskMessage = new SendMessage();
        fifthTaskMessage.setChatId(chatId);
        fifthTaskMessage.setText(taskDescription);
        // 设置带有回复选项的自定义键盘
        ReplyKeyboardMarkup replyKeyboardMarkup = getCommonReplyKeyboardMarkup(1);
        fifthTaskMessage.setReplyMarkup(replyKeyboardMarkup);
        execute(fifthTaskMessage);
    }

    /**
     * 处理第6步任务
     *
     * @param chatId          聊天id
     * @param taskDescription 任务描述
     * @throws TelegramApiException 异常
     */
    private void handleSixthStepTask(String chatId, String taskDescription) throws TelegramApiException {
        SendMessage sixthTaskMessage = new SendMessage();
        sixthTaskMessage.setChatId(chatId);
        sixthTaskMessage.setText(taskDescription);
        // 增加内联按钮
        List<List<InlineKeyboardButton>> keyboardList = new ArrayList<>();
        List<InlineKeyboardButton> keyboardButtons = new ArrayList<>();
        // 此对象表示嵌入式键盘的一个按钮，您必须完全使用可选字段之一
        InlineKeyboardButton inlineKeyboardButton = new InlineKeyboardButton();
        // 可选的。按下按钮时将打开HTTP或tg:// URL
        inlineKeyboardButton.setUrl(listenJoinGroupUrlPrefix + listenJoinGroupName);
        // 在按钮上标记文本
        inlineKeyboardButton.setText("Join");
        keyboardButtons.add(inlineKeyboardButton);
        keyboardList.add(keyboardButtons);
        InlineKeyboardMarkup inlineKeyboardMarkup = new InlineKeyboardMarkup();
        // 按钮行数组，每个行由一个InlineKeyboardButton对象数组表示，这仅适用于2016年4月9日之后发布的电报版本。较旧的客户端将显示不受支持的消息。
        inlineKeyboardMarkup.setKeyboard(keyboardList);
        // 可选的。 消息附带的嵌入式键盘。 login_url按钮表示为普通url按钮。
        sixthTaskMessage.setReplyMarkup(inlineKeyboardMarkup);
        execute(sixthTaskMessage);
    }

    /**
     * 返回到菜单页面
     *
     * @param chatId 聊天id
     */
    private void backMenuPage(String chatId) throws TelegramApiException {
        SendMessage sendMessage = new SendMessage();
        sendMessage.setChatId(chatId);
        sendMessage.setText("Please check the menu below, click the relevant button to complete the operation");
        ReplyKeyboardMarkup replyKeyboardMarkup = new ReplyKeyboardMarkup();
        //按钮行数组，每个行由一个KeyboardButton对象数组表示
        List<KeyboardRow> keyboard = new ArrayList<>();
        // 第一行
        KeyboardRow keyboardRow1 = new KeyboardRow();
        // 第一行的两个按钮
        keyboardRow1.add(menuFirstButtonText);
        keyboardRow1.add(menuSecondButtonText);
        keyboard.add(keyboardRow1);
        // 第二行
        KeyboardRow keyboardRow2 = new KeyboardRow();
        // 第一行的两个按钮
        keyboardRow2.add(menuThirdButtonText);
        keyboardRow2.add(menuFourthButtonText);
        keyboard.add(keyboardRow2);
        replyKeyboardMarkup.setKeyboard(keyboard);
        // 可选的。请求客户垂直调整键盘大小以达到最佳适合度（例如，如果只有两行按钮，则使键盘变小）。默认为false，在这种情况下，自定义键盘的高度始终与应用程序的标准键盘相同。
        replyKeyboardMarkup.setResizeKeyboard(true);
        // 可选的。如果只想向特定用户显示键盘，请使用此参数。目标：1）在Message对象的文本中@提及的用户； 2）如果机器人的消息是回复（具有reply_to_message_id），则为原始消息的发送者。
        replyKeyboardMarkup.setSelective(true);
        sendMessage.setReplyMarkup(replyKeyboardMarkup);
        execute(sendMessage);
    }

    /**
     * 返回到Earn Pen页面
     *
     * @param chatId 聊天id
     */
    private void backEarnPenMenuPage(String chatId) throws TelegramApiException {
        // 判断用户是否已完成所有任务
        int totalTasks = robotTaskService.getTotalTasks();
        int finishTasks = robotTaskService.getTotalFinishTasks(chatId);
        if (finishTasks == totalTasks) {
            SendMessage sendMessage = new SendMessage();
            sendMessage.setChatId(chatId);
            sendMessage.setText("You have completed all tasks.");
            ReplyKeyboardMarkup replyKeyboardMarkup = getCommonReplyKeyboardMarkup(1);
            sendMessage.setReplyMarkup(replyKeyboardMarkup);
            execute(sendMessage);
        } else {
            // 如果未完成所有任务，发布从第一个未完成的任务发起
            if (finishTasks == 0) {
                RobotTask robotTask = robotTaskService.getRobotTaskByTaskSort(1);
                if (null != robotTask) {
                    handleFirstStepTask(chatId, robotTask.getTaskDescription());
                }
            }
            if (finishTasks == 1) {
                RobotTask robotTask = robotTaskService.getRobotTaskByTaskSort(2);
                if (null != robotTask) {
                    handleSecondStepTask(chatId, robotTask.getTaskDescription());
                }
            }
            if (finishTasks == 2) {
                RobotTask robotTask = robotTaskService.getRobotTaskByTaskSort(3);
                if (null != robotTask) {
                    handleThirdStepTask(chatId, robotTask.getTaskDescription());
                }
            }
            if (finishTasks == 3) {
                RobotTask robotTask = robotTaskService.getRobotTaskByTaskSort(4);
                if (null != robotTask) {
                    handleFourthStepTask(chatId, robotTask.getTaskDescription(), 0, 0);
                }
            }
            if (finishTasks == 4) {
                RobotTask robotTask = robotTaskService.getRobotTaskByTaskSort(5);
                if (null != robotTask) {
                    handleFifthStepTask(chatId, robotTask.getTaskDescription());
                }
            }
            if (finishTasks == 5) {
                handleSixthTask(chatId);
            }

        }

    }

    /**
     * 发送校验奖励的信息
     *
     * @param chatId 聊天id
     */
    private void sendCongratulationMessage(String chatId) throws TelegramApiException {
        SendMessage sendMessage = new SendMessage();
        sendMessage.setChatId(chatId);
        sendMessage.setText("The airdrop will be issued to your wallet as soon as possible, if the information is true and valid.");
        execute(sendMessage);
    }

    /**
     * 发送我的奖励的信息
     *
     * @param chatId 聊天id
     */
    private void sendMyRewardsMessage(String chatId) throws TelegramApiException {
        SendMessage sendMessage = new SendMessage();
        sendMessage.setChatId(chatId);
        StringBuilder sb = new StringBuilder(1 << 5);
        sb.append("\uD83D\uDCD4 Your Submitted Data: ");
        sb.append("\n");
        // 邮箱地址
        sb.append("Email: ");
        String email = chatEmailService.getEmailByChatId(chatId);
        if (StringUtils.isNotBlank(email)) {
            sb.append(email);
        }
        sb.append("\n");
        sb.append("Discord: ");
        // 完成所有的任务获取的TP
        String discord = chatDiscordService.getDiscordByChatId(chatId);
        if (StringUtils.isNotBlank(discord)) {
            sb.append(discord);
        }
        sb.append("\n");
        sb.append("Wallet Address: ");
        String walletAddress = verifiedAddrService.getCoinAddrByChatId(chatId);
        if (StringUtils.isNotBlank(walletAddress)) {
            sb.append(walletAddress);
        }
        sb.append("\n");
        sb.append("Retweet link: ");
        String retweetUrl = chatLinkService.getChatLinkListByChatIdAndLinkCategory(chatId, 2);
        if (StringUtils.isNotBlank(retweetUrl)) {
            sb.append(retweetUrl);
        }
        sendMessage.setText(sb.toString());
        ReplyKeyboardMarkup replyKeyboardMarkup = new ReplyKeyboardMarkup();
        //按钮行数组，每个行由一个KeyboardButton对象数组表示
        List<KeyboardRow> keyboard = new ArrayList<>();
        // 第一行
        KeyboardRow keyboardRow1 = new KeyboardRow();
        keyboardRow1.add(replyButtonText);
        keyboard.add(keyboardRow1);
        replyKeyboardMarkup.setKeyboard(keyboard);
        // 可选的。请求客户垂直调整键盘大小以达到最佳适合度（例如，如果只有两行按钮，则使键盘变小）。默认为false，在这种情况下，自定义键盘的高度始终与应用程序的标准键盘相同。
        replyKeyboardMarkup.setResizeKeyboard(true);
        // 可选的。如果只想向特定用户显示键盘，请使用此参数。目标：1）在Message对象的文本中@提及的用户； 2）如果机器人的消息是回复（具有reply_to_message_id），则为原始消息的发送者。
        replyKeyboardMarkup.setSelective(true);
        sendMessage.setReplyMarkup(replyKeyboardMarkup);
        execute(sendMessage);
    }

    /**
     * 发送Pen的详细信息
     *
     * @param chatId 聊天id
     * @throws TelegramApiException
     */
    private void sendPenDetailMessage(String chatId) throws TelegramApiException {
        String systemValue = robotSystemService.getSystemValueBySystemKey(SystemKeyEnum.PENGUIN_DETAIL_MESSAGE.name());
        if (StringUtils.isNotBlank(systemValue)) {
            SendMessage sendMessage = new SendMessage();
            sendMessage.setChatId(chatId);
            sendMessage.setText(systemValue);
            execute(sendMessage);
        }
    }

    /**
     * 发送Pen下载的详细信息
     *
     * @param chatId 聊天id
     * @throws TelegramApiException
     */
    private void sendPenDownloadMessage(String chatId) throws TelegramApiException {
        SendMessage sendMessage = new SendMessage();
        sendMessage.setChatId(chatId);
        sendMessage.setText("All the rewards will be sent to your wallet app.");
        // 增加内联按钮
        List<List<InlineKeyboardButton>> keyboardList = new ArrayList<>();
        List<InlineKeyboardButton> keyboardButtons = new ArrayList<>();
        // 此对象表示嵌入式键盘的一个按钮，您必须完全使用可选字段之一
        InlineKeyboardButton inlineKeyboardButton = new InlineKeyboardButton();
        // 可选的。按下按钮时将打开HTTP或tg:// URL
        inlineKeyboardButton.setUrl(walletDownLoadUrl);
        // 在按钮上标记文本
        inlineKeyboardButton.setText("Install the app");
        keyboardButtons.add(inlineKeyboardButton);
        keyboardList.add(keyboardButtons);
        InlineKeyboardMarkup inlineKeyboardMarkup = new InlineKeyboardMarkup();
        // 按钮行数组，每个行由一个InlineKeyboardButton对象数组表示，这仅适用于2016年4月9日之后发布的电报版本。较旧的客户端将显示不受支持的消息。
        inlineKeyboardMarkup.setKeyboard(keyboardList);
        // 可选的。 消息附带的嵌入式键盘。 login_url按钮表示为普通url按钮。
        sendMessage.setReplyMarkup(inlineKeyboardMarkup);
        execute(sendMessage);
    }

}
